class Video < ActiveRecord::Base
  belongs_to :user
  acts_as_voteable
  acts_as_commentable
  @url=nil
  attr_accessible :url, :title, :description, :vote_count
  validates_presence_of  :title, :description
  validates_presence_of  :url, :on=>:create
  
  
  def linkable_url
    "http://www.youtube.com/watch?v=#{self.video_id}"
  end
  
  def url=(url)
    @url=url
  end
  
  def url
    @url
  end
  
  
  def self.most_popular(size=15)
    Video.all(:order=>"vote_count, comment_count desc", :limit=>size)
  end
  
  def self.most_recent(size=15)
    Video.all(:order=>"created_at desc", :limit=>size)  
  end
  
  def validate_on_create
    #first, check if is a youtubte url
    if VideoUtils::VideoUtils.find_video_service(@url)!=VideoUtils::YOUTUBE
      self.errors.add(:url, :video_service_not_supported)
    else
      self.video_id = VideoUtils::VideoUtils.find_video_id(@url,VideoUtils::YOUTUBE)
      if !self.video_id
        self.errors.add(:url, :video_url_malformed)  
      else
        self.errors.add(:url,:video_exists) if Video.find_by_video_id(self.video_id)
      end
    end
    
    
  end
  
end
